﻿using Timeline.Beans;
using Timeline.Inis;
using Timeline.Utils;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using Windows.ApplicationModel.Resources;

namespace Timeline.Providers {
    public class GluttonProvider : GeneralProvider {
        private Meta ParseBean(GluttonApiData bean, string titleRule, string captionRule, string order) {
            Meta meta = new Meta {
                Id = bean.Id,
                No = bean.No,
                Uhd = bean.ImgUrl,
                Thumb = bean.ThumbUrl,
                Copyright = bean.CopyrightRich,
                Story = bean.Story?.Trim(),
                CateHow = bean.CateHowId,
                CateWhat = bean.CateWhatId,
                Src = bean.SrcUrl,
                Score = bean.Score,
                Format = bean.Ext
            };
            //meta.Title = string.Format(ResourceLoader.GetForCurrentView().GetString("GluttonPhase"), bean.Phase);
            if (!string.IsNullOrEmpty(titleRule)) {
                meta.Title = titleRule.Replace("{title}", bean.Title?.Trim())
                    .Replace("{order}", order)
                    .Replace("{no}", bean.No.ToString())
                    .Replace("{phase}", bean.Phase.ToString()).Trim();
            }
            if (!string.IsNullOrEmpty(captionRule)) {
                meta.Caption = captionRule.Replace("{title}", bean.Title?.Trim())
                    .Replace("{order}", order)
                    .Replace("{no}", bean.No.ToString()).Trim();
            }
            //DateTime.TryParseExact(bean.RelDate, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out DateTime date);
            if (DateTime.TryParse(bean.RelDate, out DateTime date)) {
                meta.Date = date;
            }
            return meta;
        }

        public override async Task<bool> LoadData(CancellationToken token, Ini ai, GeneralIni gi, Go go) {
            if (string.IsNullOrEmpty(gi.GalleryApi)) {
                return false;
            }
            string order = "random".Equals(gi.Order) ? go.Seed.ToString() : gi.Order; // 随机排序使用固定种子值，便于分页加载
            string urlApi = gi.GalleryApi.Replace("{order}", order ?? "")
                .Replace("{catehow}", gi.CateHow ?? "")
                .Replace("{catewhat}", gi.CateWhat ?? "")
                .Replace("{topic}", go.FilterTopic ?? "")
                .Replace("{date}", go.CheckFilterEndDate() ? go.FilterEndDate.ToString("yyyyMMdd") : "")
                .Replace("{id}", go.CheckTargetId() ? go.TargetId : "")
                .Replace("{no}", go.CheckSplitNo() ? go.SplitNo.ToString() : "");
            LogUtil.D("LoadData() provider url: " + urlApi);
            try {
                HttpClient client = new HttpClient();
                HttpRequestMessage msgReq = new HttpRequestMessage(HttpMethod.Get, urlApi);
                msgReq.Headers.Add("Timeline-User", ai.UserEncoded());
                msgReq.Headers.Add("Timeline-Pwd", ai.PwdEncrypted());
                msgReq.Headers.Add("Timeline-Device", SysUtil.GetDeviceId());
                msgReq.Headers.Add("Timeline-Client", ai.Client ?? "");
                HttpResponseMessage res = await client.SendAsync(msgReq, token);
                string jsonData = await res.Content.ReadAsStringAsync();
                //LogUtil.D("LoadData() provider data: " + jsonData.Trim());
                GluttonApi api = JsonConvert.DeserializeObject<GluttonApi>(jsonData);
                this.accountApi = api.Auth; // 缓存帐号信息
                if (api.Status != 1) {
                    return false;
                }
                string orderStr = ResourceLoader.GetForCurrentView().GetString("Order_" + gi.Order);
                List<Meta> metasAdd = new List<Meta>();
                if (api.Extend != null && api.Extend?.Status == 1) {
                    foreach (GluttonApiData item in api.Extend.Data) {
                        metasAdd.Add(ParseBean(item, gi.TitleRule, gi.CaptionRule, orderStr));
                    }
                }
                foreach (GluttonApiData item in api.Data) {
                    metasAdd.Add(ParseBean(item, gi.TitleRule, gi.CaptionRule, orderStr));
                }
                AppendMetas(metasAdd);
                return true;
            } catch (Exception e) {
                // 情况1：任务被取消
                // System.Threading.Tasks.TaskCanceledException: A task was canceled.
                LogUtil.E("LoadData() " + e.Message);
            }
            return false;
        }
    }
}
